package io.lvdaxian.mybatis04.binding;


import io.lvdaxian.mybatis04.session.SqlSession;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * mapper 代理类
 * &#064;interface  InvocationHandler 用来实现 Proxy代理类
 *
 * @author lihh
 */
public class MapperProxy<T> implements InvocationHandler, Serializable {
  
  // 解析出的 sql session
  private final SqlSession sqlSession;
  // 表示 mapper 接口类
  private final Class<T> mapperInterface;
  
  public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface) {
    this.sqlSession = sqlSession;
    this.mapperInterface = mapperInterface;
  }
  
  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    // method.getDeclaringClass() 调用了 定义方法的类
    if (Object.class.equals(method.getDeclaringClass())) {
      // 如果是 Object的话，直接执行
      return method.invoke(args);
    } else {
      // 执行到这里 说明走代理了
      return sqlSession.selectOne(method.getDeclaringClass().getName() + "." + method.getName(), args);
    }
  }
}
